package com.example.hrandroidapp;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lib.jason.requestresponsetask.JSONHTTPPoster;
import lib.jason.requestresponsetask.HTTPUtils;

import org.json.JSONObject;
import org.json.JSONTokener;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.example.hrandroidapp.common.Constant;
import com.example.hrandroidapp.common.HRLog;
import com.example.hrandroidapp.domain.UserPO;
import com.example.hrandroidapp.preferences.CurrentServerPreference;
import com.example.hrandroidapp.preferences.UserPreference;
import com.gc.materialdesign.views.ButtonFlat;
import com.gc.materialdesign.views.ButtonRectangle;
import com.gc.materialdesign.views.ProgressWheel;
import com.gc.materialdesign.widgets.Dialog;
import com.google.gson.Gson;

public class LoginActivity extends ActionBarActivity {
	
	private ButtonRectangle btnLogin;
	private TextView tvMsg, tvCurrSvr;
	private ButtonFlat btnAdvSetting;
	private EditText etUsrId, etPwd;
	
	private List<UserPO> user;
	
	private LoginActivity activity = this;
	private String url=null;
	private ProgressWheel progressWheel;
	
	@Override
	protected void onPause() {
		super.onPause();
		stopLoading();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		setCurrentServer(); 
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		ActionBar actionBar = getSupportActionBar();
		actionBar.hide();
		
		loadViews();
		
		tvMsg.setText("");
		
		setCurrentServer();
		
		btnLogin.setTextSize(TypedValue.COMPLEX_UNIT_PX, 40); 
		btnLogin.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startLoading();
				checkLogin(etUsrId.getText().toString(), etPwd.getText().toString());
			}
		});
		
		btnAdvSetting.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				gotoSetting();
			}

		});
		
		String userId = UserPreference.getUserId(this);
		HRLog.postLogInfo("check pref userId: " + userId, "LoginActivity.onCreate");
		if(userId != null) {
			gotoMainAct();
		}
	}

	private void setCurrentServer() {
		if(CurrentServerPreference.getCurrentServer(getApplicationContext()).getSvrIP() == null) {
			tvCurrSvr.setText("No server is selected!!");
		}else {
			tvCurrSvr.setText(CurrentServerPreference.getCurrentServer(getApplicationContext()).getSvrName()); 
		}
	}

	private void gotoSetting() {
		Intent intent = new Intent(getApplicationContext(), AdvanceSettingActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.pull_in_left, R.anim.push_out_right);
	}
	private void loadViews() {
		btnAdvSetting = (ButtonFlat) findViewById(R.id.tv_adv_setting);
		tvMsg = (TextView) findViewById(R.id.tv_msg);
		etUsrId = (EditText) findViewById(R.id.et_userid);
		etPwd = (EditText) findViewById(R.id.et_pwd);
		btnLogin = (ButtonRectangle) findViewById(R.id.btn_login);
		tvCurrSvr = (TextView) findViewById(R.id.tv_current_svr);
		progressWheel = (ProgressWheel) findViewById(R.id.progress_wheel);
	}
	
	private void gotoMainAct() {
		Intent mainIntent = new Intent(getApplicationContext(), MainActivity.class);
		startActivity(mainIntent);
		overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
	}
	
	private void checkLogin(String usrName, String pwd) {
		url = getResources().getString(R.string.login_url);
		String completeUrl = "http://" + CurrentServerPreference.getCurrentServer(getApplicationContext()).getSvrIP() + ":" + Constant.PORT + url;
		
		if(CurrentServerPreference.getCurrentServer(getApplicationContext()).getSvrIP() != null) {
			HRLog.postLogInfo("login url complete: " + completeUrl, "LoginActivity.checkLogin"); 
			new HTTPUtils(this, JSONHTTPPoster.MEDIA_FORM_URLENCODED, completeUrl, populateRequestParameterMap(), new HTTPUtils.SimpleRequestResponseTaskInterface() {
	
				@Override
				public void handleResponse(String responseStr, int status) throws Exception {
					HRLog.postLogInfo("request status: " + status, "LoginActivity.checkLogin");
					
					if(status == 200) {
						Gson gson = new Gson();

						JSONObject json = new JSONObject(new JSONTokener(responseStr));
						UserPO usrPo = gson.fromJson(json.toString(), UserPO.class);
						
						tvMsg.setText("");
						usrPo.setLoginId(etUsrId.getText().toString());
						HRLog.postLogInfo("usrPO userId: " + usrPo.getUserId(), "LoginActivity.checkLogin"); 
						UserPreference.updateUser(getApplicationContext(), usrPo); 
						etUsrId.setText("");
						etPwd.setText("");
						gotoMainAct();
					}else if(status == 404) {
						
						activity.runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								Dialog dialog = new Dialog(LoginActivity.this, "Server Not Found", "Server doesn't exist or request not fould!", "OK", "", true, false);
								
								dialog.setOnCancelButtonClickListener(new OnClickListener() {
									
									@Override
									public void onClick(View v) {
										stopLoading();
									}
								});
								dialog.show();
							}
						});
					}else {
						// error occur
						activity.runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								Dialog dialog = new Dialog(LoginActivity.this, "Login Error", "Incorrect login username and password!", "OK", "", true, false);
								
								dialog.setOnCancelButtonClickListener(new OnClickListener() {
									
									@Override
									public void onClick(View v) {
										stopLoading();
									}
								});
								dialog.show();
							}
						});
					}
				}
				
			}).execute();
		}else {
			// server haven't selected!! <error message>
			Dialog dialog = new Dialog(LoginActivity.this, "No selected Server", 
					"Please select server before login...", "Go to Setting", "", true, false);
			
			dialog.setOnCancelButtonClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					gotoSetting();
				}
			});
			dialog.show();
		}
		
//		if(usrName.equals("admin") && pwd.equals("admin")) { 
//			UserPO usrPO = new UserPO((long) 1, "branchName", "name", etUsrId.getText().toString(), etPwd.getText().toString());
//			tvMsg.setText("");
//			usrPref.updateUser(usrPO); 
//			etUsrId.setText("");
//			etPwd.setText("");
//			gotoMainAct();
//		}else {
//			tvMsg.setTextColor(getResources().getColor(R.color.red));
//			tvMsg.setText("Invalid username and password");
//		}
	}
	
	public Map<String, String> populateRequestParameterMap() {
//		String paramString = "loginId=" + etUsrId.getText().toString() + "&password=" + etPwd.getText().toString();
		 Map<String, String> parametersMap = new HashMap<String, String>();        
		 parametersMap.put("loginId", etUsrId.getText().toString()); 
		 parametersMap.put("password", etPwd.getText().toString());
		 return parametersMap;
	}
	
	private void startLoading() {
		progressWheel.setVisibility(View.VISIBLE);
		progressWheel.spin();
	}
	
	private void stopLoading() {
		progressWheel.stopSpinning();
		progressWheel.setVisibility(View.GONE);
		etUsrId.setText("");
		etPwd.setText("");
	}
	
}
